// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import 'babel-polyfill'
import Vue from 'vue'
import vuet from '../vuet'
import VueRouter from 'vue-router'
import store from '../vuex'
import * as routers from '../routers'
import * as filters from '../filters'
import FastClick from '../assets/dep/fastclick'
import * as request from '../request'
import * as utils from '../utils'
import 'mint-ui/lib/style.css'
import {Toast, MessageBox, Indicator, DatetimePicker} from 'mint-ui'
import config from '../config'
import * as dictionary from '../dictionary'
import native from '../native'
import * as storage from '../storage'
import * as validator from '../validator'
import * as rem from '../rem'
import * as PromiseExtend from '../PromiseExtend'

require('../assets/style/iconfont.css')
require('../assets/style/global.css')
require('../assets/style/css.css')
Vue.component(DatetimePicker.name, DatetimePicker)
Vue.use(VueRouter)
var components = require('../components')

// 去除手机的300毫秒点击延迟
FastClick.attach(document.body)

rem.init() // 初始化rem单位
PromiseExtend.init() // 初始化Promise的扩展
components.regist(Vue) // 全局注册组件

// 挂载全局参数与方法
Vue.prototype.$deviceType = utils.getDeviceType()
Vue.prototype.$request = request
Vue.prototype.$utils = utils
Vue.prototype.$toast = Toast
Vue.prototype.$indicator = Indicator
Vue.prototype.$messageBox = MessageBox
Vue.prototype.$config = config
Vue.prototype.$dictionary = dictionary
Vue.prototype.$native = native
Vue.prototype.$storage = storage
Vue.prototype.$validator = validator

// 实例化Vue的filter
Object.keys(filters).forEach(k => Vue.filter(k, filters[k]))

// 实例化VueRouter
const router = new VueRouter({
  mode: 'history',
  base: '/wap/',
  routes: routers.list,
  scrollBehavior: routers.scrollBehavior
})

let entryUrl = window.location.href
storage.setEntryUrl(entryUrl) // 设置当前入口地址

// 为保证hbuilder的plus对象在使用时已初始化，在其初始化完成后再启动应用
// document.addEventListener('plusready', function () {
//   new Vue({
//     router,
//     store
//   }).$mount('#app')
// })
// if (config.nativeType == 'pc') {
//   storage.setKey('19607a26ac02059db99b8776d038fc15') // 测试用
// }
console.log(native.getType())
router.beforeEach(async (to, from, next) => {
  if (to.name == 'setting-download') {
    next()
  }
  console.log('beforeEach', to.fullPath, to.query.fkmid)
  // let url = config.website + '/wap' + to.fullPath
  // native.weixinShare(url)
  let fkmid = to.query.fkmid || utils.getQueryString('fkmid') || null
  if (fkmid) {
    storage.setFkmid(fkmid)
  }
  // console.log('fkmid', fkmid)
  if (to.meta.login) { // 需要先登录才能访问的页面
    let key = storage.getKey()
    // 需要的登录后才能访问
    if (!key || key == '' || key == 'null') {
      key = await request.getKey()
      if (key) {
        storage.setKey(key)
        next()
      } else {
        // if (utils.getDeviceType() == 'wx-Android' || utils.getDeviceType() == 'wx-iPhone') {
        //   native.weixinLogin(fkmid) // 微信授权后才能取到key
        // } else {
        next({name: 'login-password'})
        // }
      }
    } else {
      // if (!storage.getMemberInfo()) {
      //   let memberInfo = await request.getMemberInfo()
      let memberInfo = await request.getMemberInfoByKey()
      if (!memberInfo) { // 后台或数据库直接删除用户导致key失效, 需要重新登录
        storage.delKey()
        storage.setAuthed(false)
        storage.delMemberInfo()
        utils.delCookie('key')
        next({name: 'login-password'})
      }
      storage.setMemberInfo(memberInfo)
      console.log('member info new')
      // 将用户信息绑定到推送服务器
      if (window.api) {
        var push = window.api.require('push')
        if (push) {
          push.bind({
            userName: memberInfo.member_name,
            userId: memberInfo.member_id
          }, function (ret, err) {
            if (ret) {
              console.debug('绑定推送用户成功', ret)
            } else {
              console.debug('绑定推送用户失败', err)
            }
          })
        }
      }
      // }
    }
  }
  if (to.meta.auth) { // 需要完善资料后才能访问的页面
    let auth = storage.getAuthed()
    if (!auth || auth == '' || auth == 'null') {
      let authStatus = await request.getAuth()
      if (authStatus != '1') { // 未完善过
        let query = to.query
        query.to = to.name
        query.fkmid = fkmid
        next({name: 'login-password', query: query, params: to.params})
      } else {
        storage.setAuthed(true)
        next()
      }
    }
  }
  next()
})

router.afterEach((to, from) => {
  setTimeout(() => {
    native.weixinShare(window.location.href) // 每个页面需要重新进行微信配置
    let fkmid = utils.getQueryString('fkmid')
    if (fkmid) {
      request.bindFriend(fkmid).then(data => {
        console.log('绑定朋友成功, fkmid:', fkmid)
      }).catch(e => {
        console.error('绑定上下级失败', e)
      })
    }
  }, 200)
})

// 全局注入混合
Vue.mixin({
  mounted() {
    window.scrollTo(1, 1) // 移动1px，解决浏览器后退时，需要滚动下页面才会渲染页面的bug
  }
})

let app = new Vue({
  router,
  vuet,
  store
})

// 如果是app（apicloud打包）,等app基础类api加载完成后再进入程序，确保每个页面调用api时，都已经可用。
if (utils.getDeviceType() == 'APICloud') {
  window.apiready = function () {
    app.$mount('#app')
  }
} else {
  app.$mount('#app')
}

export {app, Vue, router, store}
